<?php

namespace App\Admin\Controllers\Auth;

use App\Admin\Controllers\Controller;
use App\Admin\Utils\Admin;
use App\Admin\Models\VueRouter;
use App\Admin\Models\VueAdminUserRouter;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    public function username()
    {
        return 'username';
    }

    protected function authenticated(Request $request, $user)
    {
        if (!Admin::isAdministrator()) {
            $vueRouterList = app(VueRouter::class)->treeWithAuth()->toTree();
            app(VueAdminUserRouter::class)->createVueAdminUserRouter($vueRouterList, Admin::user()->id);
        }
        return $this->created();
    }

    public function logout()
    {
        if (config()->get('app.env')=='production') {
            $this->guard()->logout();
        }
        return $this->noContent();
    }

    /**
     * @return \Illuminate\Contracts\Auth\Guard
     */
    protected function guard()
    {
        if (config()->get('app.env')=='production') {
            return Admin::guard();
        }
        $user = \Mockery::mock(Authenticatable::class);
        $user->shouldReceive('getAuthIdentifier')->andReturn(1);

        $guard = \Mockery::mock(Guard::class);
        $guard->shouldReceive('check')->andReturn(true);
        $guard->shouldReceive('user')->andReturn($user);
        $guard->shouldReceive('validate')->andReturn(false);
        $guard->shouldReceive('attempt')->andReturnUsing(function (array $credentials, $remember) use ($user) {
            $user->shouldReceive('getAuthPassword')->andReturn($credentials['password']);
            return true;
        });

        return $guard;
    }

    protected function validateLogin(Request $request)
    {
        if (config()->get('app.env')=='production') {
            $rules = [
                $this->username() => 'required|string',
                'password' => 'required|string',
            ];

            if (config('admin.system_basic.admin_login_captcha', '1') === '1') {
                $rules['captcha'] = 'required|captcha_api:'.$request->input('key');
            }

            $request->validate($rules, ['captcha_api' => '验证码 错误。'], ['captcha' => '验证码']);
        }
    }
}
